package com.mf.elephant.common.framework.dao;

import com.mf.elephant.common.framework.dao.tools.DataTransferUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * mybatis-基础DAO
 * User: zhaoming
 * Date: 2016-06-24
 * To change this template use File | Settings | File Templates.
 **/

public class BaseDao<T extends Object> extends SqlSessionDaoSupport {

    public Logger logger = LoggerFactory.getLogger(getClass());

    // 批处理操作最大数量
    private static final int MAX_BATCH = 600;

    /**
     * 新增数据
     * @param statement SQLMapper - Key
     * @param entity 实体对象
     * @return 执行结果
     */
    public boolean insert(String statement, T entity){
        if(entity == null){
            logger.error("实体对象为空");
            throw new RuntimeException("实体对象为空");
        }
        return this.getSqlSession().insert(statement, entity) > 0 ? true : false;
    }

    /**
     * 批量新增数据
     * @param statement SQLMapper - Key
     * @param entities 实体对象列表
     * @return 执行结果
     */
    public boolean insert(String statement, List<T> entities){
        if(CollectionUtils.isEmpty(entities)){
            logger.error("实体对象列表为空");
            throw new RuntimeException("实体对象列表为空");
        }
        if(entities.size() > MAX_BATCH){
            logger.error("实体对象列表数量已超过最大数量");
            throw new RuntimeException("实体对象列表数量已超过最大数量");
        }
        return this.getSqlSession().insert(statement, entities) > 0 ? true : false;
    }

    /**
     * 更新数据
     * @param statement SQLMapper - Key
     * @param entity 实体对象
     * @return 执行结果
     */
    public boolean update(String statement, T entity) {
        if(entity == null){
            logger.error("实体对象为空");
            throw new RuntimeException("实体对象为空");
        }
        return this.getSqlSession().update(statement, entity) > 0 ? true : false;
    }

    /**
     * 删除数据
     * @param statement SQLMapper - Key
     * @param entity 实体对象
     * @return 执行结果
     */
    public boolean delete(String statement, T entity) {
        if(entity == null){
            logger.error("实体对象为空");
            throw new RuntimeException("实体对象为空");
        }
        return this.getSqlSession().delete(statement, entity) > 0 ? true : false;
    }

    /**
     * 批量删除数据
     * @param statement SQLMapper - Key
     * @param entities 实体对象列表
     * @return 执行结果
     */
    public boolean delete(String statement, List<T> entities) {
        if(CollectionUtils.isEmpty(entities)){
            logger.error("实体对象列表为空");
            throw new RuntimeException("实体对象列表为空");
        }
        if(entities.size() > MAX_BATCH){
            logger.error("实体对象列表数量已超过最大数量");
            throw new RuntimeException("实体对象列表数量已超过最大数量");
        }
        return this.getSqlSession().delete(statement, entities) > 0 ? true : false;
    }

    /**
     * 批量删除数据
     *
     * @param statement SQLMapper - Key
     * @param entities 实体对象列表
     * @return 执行结果
     */
    public boolean deleteLogically(String statement, List<T> entities) {
        if(CollectionUtils.isEmpty(entities)){
            logger.error("实体对象列表为空");
            throw new RuntimeException("实体对象列表为空");
        }
        if(entities.size() > MAX_BATCH){
            logger.error("实体对象列表数量已超过最大数量");
            throw new RuntimeException("实体对象列表数量已超过最大数量");
        }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        try {
            T entity = entities.get(0);
            paramMap.putAll(DataTransferUtil.voToMap(entity));

            List<Object> ids = new ArrayList<Object>();
            for(T t : entities){
                boolean flag = false;
                if(!flag) {
                    Field[] fields = entity.getClass().getDeclaredFields();
                    for (Field field : fields) {
                        Id idAnnotation = field.getAnnotation(Id.class);
                        if (idAnnotation != null) {
                            field.setAccessible(true);
                            ids.add(field.get(t));
                            flag = true;
                            break;
                        }
                    }
                }
                if(!flag) {
                    Field[] superFields = entity.getClass().getSuperclass().getDeclaredFields();
                    for (Field field : superFields) {
                        Id idAnnotation = field.getAnnotation(Id.class);
                        if (idAnnotation != null) {
                            field.setAccessible(true);
                            ids.add(field.get(t));
                            break;
                        }
                    }
                }
            }
            paramMap.put("ids", ids);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return this.getSqlSession().update(statement, paramMap) > 0 ? true : false;
    }

    /**
     * 查询一条数据
     * @param statement SQLMapper - Key
     * @param entity 实体对象
     * @return 实体对象
     */
    public T selectOne(String statement, T entity) {
        if(entity == null){
            logger.error("实体对象为空");
            throw new RuntimeException("实体对象为空");
        }
        return (T)this.getSqlSession().selectOne(statement, entity);
    }

    /**
     * 查询多条数据
     * @param statement SQLMapper - Key
     * @param entity 实体对象
     * @return 实体对象列表
     */
    public List<T> selectList(String statement, T entity) {
        return this.getSqlSession().selectList(statement, entity);
    }

    /**
     * 查询全部数据
     * @param statement SQLMapper - Key
     * @return 实体对象列表
     */
    public List<T> selectList(String statement) {
        return this.getSqlSession().selectList(statement);
    }

    /**
     * 统计数据数量
     * @param statement SQLMapper - Key
     * @param entity 实体对象
     * @return 数据数量
     */
    public Integer selectCount(String statement, T entity) {
        return (Integer)this.getSqlSession().selectOne(statement, entity);
    }

    /**
     * 分页查询
     * @param sqlStatement SQLMapper - sqlKey
     * @param countStatement SQLMapper - countKey
     * @param pageBean 分页对象
     * @param entity 实体对象
     * @return 分页对象
     */
    public PageBean<T> pageQuery(String sqlStatement, String countStatement, PageBean<T> pageBean, Object entity) {
        try {
            if (entity == null) {
                return pageQuery(sqlStatement, countStatement, pageBean, null);
            } else if (entity instanceof Map) {
                return pageQuery(sqlStatement, countStatement, pageBean, (Map<?, ?>) entity);
            } else {
                return pageQuery(sqlStatement, countStatement, pageBean, DataTransferUtil.voToMap(entity));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private PageBean<T> pageQuery(String statementName, String countStatementName, PageBean<T> pageBean, Map<?, ?> entity) {
        //总数
        int totalCount = this.getSqlSession().selectOne(countStatementName, entity);
        //为0时，返回一个新的page
        if (totalCount == 0) {
            return new PageBean<T>();
        }
        Map filter = new HashMap();
        if (entity != null) {
            filter.putAll(entity);
        }
        //_sorts名固定写法，与com.jd.las.im.common.dao.interceptor.PaginationInterceptor中进行映射
        filter.put("_sorts", pageBean.getSortItemMap());
        List<T> list = this.getSqlSession().selectList(statementName, filter, new RowBounds((pageBean.getPage() - 1) * pageBean.getPageSize(), pageBean.getPageSize()));

        PageBean<T> result = new PageBean<T>(pageBean.getPage(), totalCount, pageBean.getPageSize());
        result.addAll(list);
        return result;
    }
}
